<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>js异步执行，宏任务和微任务 | 雨落</title>
  <meta name="description" content="什么是宏任务和微任务宏任务和微任务都是属于异步任务 说到宏任务和微任务，我们就不得不提 Event Loop(事件循环) 了 js本质是单线程，只有执行完当前任务才会执行下一个任务，其本质是：     1、非阻塞性的任务采取同步的方式，直接在主线程的执行栈完成。     2、阻塞性的任务都会采用异步来执行，异步的工作一般会交给其他线程完成，然后回调函数会放到事件队列中 当主线程的任务执行完了(执行">
<meta property="og:type" content="article">
<meta property="og:title" content="js异步执行，宏任务和微任务">
<meta property="og:url" content="https://gitee.com/Yu-Luoboke/2020/12/09/js%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1-%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/index.html">
<meta property="og:site_name" content="雨落">
<meta property="og:description" content="什么是宏任务和微任务宏任务和微任务都是属于异步任务 说到宏任务和微任务，我们就不得不提 Event Loop(事件循环) 了 js本质是单线程，只有执行完当前任务才会执行下一个任务，其本质是：     1、非阻塞性的任务采取同步的方式，直接在主线程的执行栈完成。     2、阻塞性的任务都会采用异步来执行，异步的工作一般会交给其他线程完成，然后回调函数会放到事件队列中 当主线程的任务执行完了(执行">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/blog/images/js%E5%8D%95%E7%BA%BF%E7%A8%8B.png">
<meta property="og:image" content="https://gitee.com/blog/images/%E5%AE%8F%E4%BB%BB%E5%8A%A1.png">
<meta property="og:image" content="https://gitee.com/blog/images/%E5%BE%AE%E4%BB%BB%E5%8A%A1.png">
<meta property="article:published_time" content="2020-12-09T02:47:18.000Z">
<meta property="article:modified_time" content="2021-01-08T07:54:02.556Z">
<meta property="article:author" content="lianghongming">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/blog/images/js%E5%8D%95%E7%BA%BF%E7%A8%8B.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://gitee.com/Yu-Luoboke/2020/12/09/js%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1-%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/index.html">
  
    <link rel="alternate" href="/atom.xml" title="雨落" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/blog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 5.2.0"></head>


<body class="main-center" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="http://yu-luoboke.gitee.io/blog" target="_blank">
          <img class="img-circle img-rotate" src="/blog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">雨落</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">前端开发-奋斗青年</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> GuangZhou, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/blog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="http://yu-luoboke.gitee.io/blog" target="_blank" title="Github" ><i class="icon icon-github"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎交流与分享经验!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Git/">Git</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/HTML-CSS/">HTML + CSS</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/JVM%EF%BC%88Java%E8%99%9A%E6%8B%9F%E6%9C%BA%EF%BC%89-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95/">JVM（Java虚拟机）-垃圾回收算法</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Node/">Node</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Project/">Project</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/React/">React</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/SVN/">SVN</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Vue-typescript/">Vue-typescript</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/gitee/">gitee</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/iOS/">iOS</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/js/">js</a><span class="category-list-count">12</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/vue/">vue</a><span class="category-list-count">13</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/web-serve%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8/">web serve静态资源服务器</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/webpack/">webpack</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E5%89%8D%E7%AB%AF%E8%87%AA%E5%8A%A8%E5%8C%96/">前端自动化</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E5%B0%8F%E7%A8%8B%E5%BA%8F/">小程序</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E7%A7%BB%E5%8A%A8%E7%AB%AF/">移动端</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E7%BB%8F%E9%AA%8C/">经验</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a><span class="category-list-count">4</span></li></ul>
    </div>
  </div>


    
      

    
      
    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2024/04/">四月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2023/11/">十一月 2023</a><span class="archive-list-count">8</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2023/09/">九月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/12/">十二月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/08/">八月 2022</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/07/">七月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/06/">六月 2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/04/">四月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/01/">一月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/12/">十二月 2021</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/11/">十一月 2021</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/10/">十月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/04/">四月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/03/">三月 2021</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/02/">二月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/01/">一月 2021</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/12/">十二月 2020</a><span class="archive-list-count">15</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/HTML-CSS/">HTML + CSS</a>
              </p>
              <p class="item-title">
                <a href="/blog/2024/04/15/%E6%8B%96%E5%8A%A8%E5%92%8C%E7%82%B9%E5%87%BB%E5%BC%B9%E7%AA%97/" class="title">拖动和点击弹窗</a>
              </p>
              <p class="item-date">
                <time datetime="2024-04-15T12:22:06.000Z" itemprop="datePublished">2024-04-15</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/html%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">html面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:58:27.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/css%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">css面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:57:17.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/js%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">js面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:37:30.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:29:49.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-js异步任务-宏任务和微任务" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      js异步执行，宏任务和微任务
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/blog/2020/12/09/js%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1-%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/" class="article-date">
	  <time datetime="2020-12-09T02:47:18.000Z" itemprop="datePublished">2020-12-09</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/blog/categories/js/">js</a>
  </span>

        

        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/blog/2020/12/09/js%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1-%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h2 id="什么是宏任务和微任务"><a href="#什么是宏任务和微任务" class="headerlink" title="什么是宏任务和微任务"></a>什么是宏任务和微任务</h2><pre><code>宏任务和微任务都是属于异步任务
说到宏任务和微任务，我们就不得不提 Event Loop(事件循环) 了
js本质是单线程，只有执行完当前任务才会执行下一个任务，其本质是：
    1、非阻塞性的任务采取同步的方式，直接在主线程的执行栈完成。
    2、阻塞性的任务都会采用异步来执行，异步的工作一般会交给其他线程完成，然后回调函数会放到事件队列中
当主线程的任务执行完了(执行栈空了)，JS会去询问事件队列
执行一个宏任务(先执行同步代码)(相当于去银行办理业务时的&quot;取号操作&quot;) ===》 执行所有的微任务(&quot;办理业务&quot;) ===》 UI render ===》执行下一个宏任务……（等业务办理完（微任务执行完）之后才能办理下一个取号的人（执行下一个宏任务））</code></pre>
<h2 id="为什么微任务比宏任务先执行"><a href="#为什么微任务比宏任务先执行" class="headerlink" title="为什么微任务比宏任务先执行"></a>为什么微任务比宏任务先执行</h2><ul>
<li>主要是因为事件循环会先判断消息队列中是否有微任务；浏览器端所有的宏任务都在一个时间队列里面执行，事件循环监听着执行栈和消息队列，当执行栈为空时，从消息队列取出一个事件时，如果有微任务，先把微任务执行完，然后才开始执行事件（即宏任务）<br>1、宏任务每次只取一个<br>2、微任务执行多个<br>3、微任务会放在当前时间循环的末尾（这就导致了微任务比宏任务先执行）</li>
</ul>
<h2 id="eventLoop事件循环"><a href="#eventLoop事件循环" class="headerlink" title="eventLoop事件循环"></a>eventLoop事件循环</h2><ul>
<li>代码开始执行的时候，任务先进入执行栈(call back)中，如果是同步任务，则执行该任务，并输出结果，该任务出栈，执行栈开始执行下一个任务。执行栈在执行时，如果发现该任务是宏任务，那么该宏任务进入宏任务队列，如果是微任务，那么进入微任务队列，当执行栈的任务执行完，执行栈为空时，首先会来到微任务队列中，将微任务放到执行栈中执行，如果在微任务执行的过程中添加微任务，那么添加的微任务也会在本次循环中执行，即在事件循环前调用。当微任务也执行完时，事件循环判断到执行栈和微任务队列都为空，那么将循环到宏任务队列，将宏任务放入执行栈中执行，直到宏任务也执行完，代码就执行完毕</li>
</ul>
<p><img src="/blog/images/js%E5%8D%95%E7%BA%BF%E7%A8%8B.png" alt="js单线程" title="js单线程"></p>
<h2 id="宏任务和微任务包括哪些"><a href="#宏任务和微任务包括哪些" class="headerlink" title="宏任务和微任务包括哪些"></a>宏任务和微任务包括哪些</h2><ul>
<li><p>宏任务（由宿主：node，浏览器发起）</p>
<p>  <img src="/blog/images/%E5%AE%8F%E4%BB%BB%E5%8A%A1.png" alt="宏任务" title="宏任务"></p>
</li>
<li><p>微任务（由js引擎发起）</p>
<p>  <img src="/blog/images/%E5%BE%AE%E4%BB%BB%E5%8A%A1.png" alt="微任务" title="微任务"></p>
</li>
<li><p><font color=red>执行的顺序：先同步后异步，先微任务后宏任务</font></p>
</li>
</ul>
<h2 id="案例（同步代码和异步代码）"><a href="#案例（同步代码和异步代码）" class="headerlink" title="案例（同步代码和异步代码）"></a>案例（同步代码和异步代码）</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">1 console.log(&quot;AAAA&quot;);                           同步代码：console.log()</span><br><span class="line">2 setTimeout(() &#x3D;&gt; console.log(&quot;BBBB&quot;), 1000);   setTimeout()是同步代码,定时器里面的代码是异步代码</span><br><span class="line">3 const start &#x3D; new Date();                      同步</span><br><span class="line">4 while (new Date() - start &lt; 3000) &#123;&#125;           同步</span><br><span class="line">5 console.log(&quot;CCCC&quot;);                           同步</span><br><span class="line">6 setTimeout(() &#x3D;&gt; console.log(&quot;DDDD&quot;), 0);      外边是同步，定时器里面的代码是异步</span><br><span class="line">7 new Promise((resolve, reject) &#x3D;&gt; &#123;         new promise的参数是同步，resolve和reject回调函数里面的代码（即then里面的代码)是异步</span><br><span class="line">8   console.log(&quot;EEEE&quot;);</span><br><span class="line">9   foo.bar(100);</span><br><span class="line">10 &#125;)</span><br><span class="line">11 .then(() &#x3D;&gt; console.log(&quot;FFFF&quot;))</span><br><span class="line">12 .then(() &#x3D;&gt; console.log(&quot;GGGG&quot;))</span><br><span class="line">13 .catch(() &#x3D;&gt; console.log(&quot;HHHH&quot;));</span><br><span class="line">14 console.log(&quot;IIII&quot;);   同步</span><br></pre></td></tr></table></figure>
<ul>
<li><p>输出结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">AAAA</span><br><span class="line">CCCC</span><br><span class="line">EEEE</span><br><span class="line">IIII</span><br><span class="line">HHHH</span><br><span class="line">BBBB</span><br><span class="line">DDDD</span><br></pre></td></tr></table></figure></li>
<li><p>解析（同步任务在线程中执行完，查看事件队列中是否有）<br>  一开始代码执行，输出AAAA</p>
<p>  第二行代码开启一个计时器t1(一个称呼)，这是一个<font color=red>异步任务且是宏任务</font>，需要等到1秒后提交(进入事件队列中排队等待)。</p>
<p>  第四行是个while语句，需要等待3秒后才能执行下面的代码,这里有个问题，就是3秒后上一个计时器t1的提交时间已经过了，但是线程上的任务还没有执行结束，所以暂时不能打印结果，所以它排在宏任务的最前面了。</p>
<p>  第五行又输出CCCC</p>
<p>  第六行又开启一个计时器t2（称呼），它提交的时间是0秒（其实每个浏览器器有默认最小时间的，暂时忽略），但是之前的t1任务还没有执行，还在等待，所以t2就排在t1的后面。（t2排在t1后面的原因是while造成的）都还需要等待，因为线程上的任务还没执行完毕。(都在事件队列中等待)</p>
<p>  第七行new Promise将执行promise函数，它参数是一个回调函数，这个回调函数内的代码是同步的，它的异步核心在于resolve和reject，同时这个异步任务（resolve，reject）在任务队列中属于<font color=red>微任务</font>，是优先于宏任务执行的，(不管宏任务有多急，反正我是VIP)。所以先直接打印输出同步代码EEEE。第九行中的代码是个不存在的对象，这个错误要抛给reject这个状态（相当于执行了reject回调函数），也就是catch去处理，但是它是<font color=red>异步的且是微任务</font>，只有等到线程上的任务执行完毕，立马执行它，不管宏任务（计时器，ajax等）等待多久了。</p>
<p>  第十四行，这是线程上的最后一个任务，打印输出 IIII</p>
<p>  我们先找出线程上的同步代码，将结果依次排列出来：AAAA CCCC EEEE IIII</p>
<p>  然后我们再找出所有异步任务中的微任务 把结果打印出来 HHHH（执行完线程里面的任务，查看事件队列中的任务是否执行完（即有回调函数），如果有则进入线程）</p>
<p>  最后我们再找出异步中的所有宏任务，这里t1排在前面t2排在后面（这个原因是while造成的），输出结果顺序是 BBBB DDDD</p>
<p>  所以综上 结果是 AAAA CCCC EEEE IIII HHHH BBBB DDDD</p>
</li>
</ul>
<p><strong>js异步执行，宏任务和微任务</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">1 async function async1() &#123;</span><br><span class="line">2 console.log(&quot;AAAA&quot;);</span><br><span class="line">3 async2();</span><br><span class="line">4 console.log(&quot;BBBB&quot;);</span><br><span class="line">5 &#125;</span><br><span class="line">6 async function async2() &#123;</span><br><span class="line">7  console.log(&quot;CCCC&quot;);</span><br><span class="line">8 &#125;</span><br><span class="line">9  console.log(&quot;DDDD&quot;);</span><br><span class="line">10 setTimeout(function () &#123;</span><br><span class="line">11 	console.log(&quot;FFFF&quot;);</span><br><span class="line">12 &#125;, 0);</span><br><span class="line">13 async1();</span><br><span class="line">14 new Promise(function (resolve) &#123;</span><br><span class="line">15 	console.log(&quot;GGGG&quot;);</span><br><span class="line">16  resolve();</span><br><span class="line">17 &#125;).then(function () &#123;</span><br><span class="line">18  console.log(&quot;HHHH&quot;);</span><br><span class="line">19 &#125;);</span><br><span class="line">20 console.log(&quot;IIII&quot;);</span><br></pre></td></tr></table></figure>

<p>答案解析</p>
<p>浏览器下 输出结果的先后顺序是</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">DDDD</span><br><span class="line">AAAA</span><br><span class="line">CCCC</span><br><span class="line">BBBB</span><br><span class="line">GGGG</span><br><span class="line">IIII</span><br><span class="line">HHHH</span><br><span class="line">FFFF</span><br></pre></td></tr></table></figure>

<p>这道题考察重点是  js异步执行 宏任务 微任务.</p>
<p>这道题的坑就在于 async 中如果没有await，那么它就是一个纯同步函数。</p>
<p>这道题的起始代码在第9行，输出<code>DDDD</code></p>
<p>第10 行计时器开启一个异步任务 t1（一个称呼），这个任务且为宏任务,大概等到 0 秒左右把它提交到任务队列</p>
<p>第十三行，async1() 这里大家需要注意函数内部没有 await ，那该函数就是一个普通函数，里面没有异步任务，所以打印 AAAA,在这个函数内部继续执行 async2 打印 CCCC,接着打印 BBBB,至此 async1 执行完毕，在这里大家可以考虑 async1 中加了 await 怎么办？</p>
<p>第十四行，new Promise 本身是同步函数，打印 GGGG ,执行完毕后开启一个异步任务，由于是 resolve 状态，所以执行then 回调中的第一个函数，同时大家要注意，promise 开启的是异步任务，优先级高于宏任务</p>
<p>接着打印 IIII，到此，第一轮代码执行完毕。</p>
<p>然后通过 event loop 去任务队列中查找任务，按照这种队列的先后顺序依次打印 HHHH, FFFF</p>
<p>所以最终打印结果  DDDD,AAAA,CCCC,BBBB,GGGG,IIII,HHHH,FFFF</p>
<p>函数里面添加await</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">1 async function async1() &#123;</span><br><span class="line">2 console.log(&quot;AAAA&quot;);</span><br><span class="line">3 await async2();</span><br><span class="line">4 console.log(&quot;BBBB&quot;);</span><br><span class="line">5 &#125;</span><br><span class="line">6 async function async2() &#123;</span><br><span class="line">7  console.log(&quot;CCCC&quot;);</span><br><span class="line">8 &#125;</span><br><span class="line">9  console.log(&quot;DDDD&quot;);</span><br><span class="line">10 setTimeout(function () &#123;</span><br><span class="line">11 	console.log(&quot;FFFF&quot;);</span><br><span class="line">12 &#125;, 0);</span><br><span class="line">13 async1();</span><br><span class="line">14 new Promise(function (resolve) &#123;</span><br><span class="line">15 	console.log(&quot;GGGG&quot;);</span><br><span class="line">16  resolve();</span><br><span class="line">17 &#125;).then(function () &#123;</span><br><span class="line">18  console.log(&quot;HHHH&quot;);</span><br><span class="line">19 &#125;); </span><br><span class="line">20 console.log(&quot;IIII&quot;);</span><br></pre></td></tr></table></figure>
<p>输出结果是：DACGIBHF</p>
<p>个人理解：<br>添加了await后，表示该函数里面有异步操作，只有等async2执行完，await得到了结果，才会往下执行，async2函数被async修饰，说明该函数会返回一个promise，<br>等async2执行完，那么返回的promise状态就已经变为成功，await下面的代码就不会被阻塞了，就可以正常执行，这时那么就会输出BBBB，但是因为有它的同步任务，<br>所以先输出GI，再输出B</p>

      
    </div>
    <div class="article-footer">
      <!-- <blockquote class="mt-2x"> -->
  <!-- <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/Yu-Luoboke/2020/12/09/js%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1-%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/" title="js异步执行，宏任务和微任务" target="_blank" rel="external">https://gitee.com/Yu-Luoboke/2020/12/09/js%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1-%E5%AE%8F%E4%BB%BB%E5%8A%A1%E5%92%8C%E5%BE%AE%E4%BB%BB%E5%8A%A1/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul> -->
<!-- </blockquote> -->


<!-- <div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="http://yu-luoboke.gitee.io/blog" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/blog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="http://yu-luoboke.gitee.io/blog" target="_blank"><span class="text-dark">雨落</span><small class="ml-1x">前端开发-奋斗青年</small></a></h3>
        <div>前端经验总结。</div>
      </div>
    </figure>
  </div>
</div> -->


    </div>
  </article>
  
    

  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/blog/2020/12/09/gitee%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/" title="gitee搭建博客"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    
  </ul>
  
  
  
  <div class="bar-right">
    
  </div>
  </div>
</nav>
  


</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="http://yu-luoboke.gitee.io/blog" target="_blank" title="Github" ><i class="icon icon-github"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2024 lianghongming
        
        <div class="publishby">
        	Theme by <a href="https://gitee.com/Yu-Luoboke/blog" target="_blank"> blog </a>base on <a href="https://gitee.com/Yu-Luoboke/blog" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/blog/js/plugin.min.js"></script>


<script src="/blog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/blog/',
        CONTENT_URL: '/blog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/blog/js/insight.js"></script>






   









</body>
</html>